import { useMemo, useRef, useState } from 'react';
import _ from 'lodash';
// import { WithNormalRender } from '@/biz-components/hoc-form/with-normal';
import { WithNormalRender } from "@ey-render/hoc-form";
import { getSubmitFormValues } from '@ey-utils/utils/formily-utils/getSubmitFormValues';
import { onFieldChange, onFieldInit, onFormMount } from '@formily/core';
import { fileBoxPage, fileBoxList, updateBoxsByPosition } from './services';
import { message, Button, Modal } from 'antd';
import ReactToPrint from 'react-to-print';
import BarPrint from '../file-box-print/components/bar-print';
import { Form } from '@formily/core/esm/models';
import components from "@/components/schema-form-render/schema-components-registed/components-biz";
import {toJS} from "@formily/reactive";

const ArchivesCabinet = () => {
  const [submited, setSubmited] = useState(false);
  const [printList, setPrintList] = useState<any[]>([]);
  const formRef = useRef<Form<any>>();
  const printContentRef = useRef<any>();
  const printCmpntRef = useRef<any>();

  const BillFormLayout = useMemo(() => {
    return WithNormalRender({
      filedConfig: {},
      components: {
        ...components,
      },
    });
  }, []);

  // 提交
  const submit = async () => {
    const form = formRef.current;
    const formValues: any = form && await getSubmitFormValues(form);

    if (formValues) {
      const params = {
        ...formValues,
        pageCode: 'ArcvFileBox_Cbnt_C'
      };
      const res: any = await updateBoxsByPosition(params);

      const { success } = res || {};

      if (success) {
        form?.reset();
        setSubmited(true);
        setPrintList(formValues.fileBox);
        getNewFileBox(formValues.fileBox?.map((o: any) => o.code));
        message.success('入柜成功');
      }

      return res;
    }

    return {
      success: false,
    };
  };

  const getNewFileBox = (code: string[]) => {
    fileBoxList({
      "pageCode": "ArcvFileBox_L",
      code
    }).then((res: any) => {
      setPrintList(res.result || []);
      printCmpntRef.current?.handlePrint();
    })
  }

  const searchFileBox = _.debounce(async (form: Form<any>, code: string) => {
    const { fileBox, belongCo } = form.values;

    if (!belongCo) {
      message.error('请先选择保管公司');
      return;
    }

    const res: any = await fileBoxPage({
      pageNo: 1,
      pageSize: 20,
      queryKeys: {
          code,
          coCode: belongCo,
          pageCode: "ArcvFileBox_L1"
      }
    });

    if (res.success && !!res.result?.content?.length) {
      const target = res.result.content[0];
      if(toJS(fileBox).find((it:any) => it.code === target.code)) {
        message.error(`档案盒 ${target.code} 已在档案盒列表`);
        form.setValuesIn('code', undefined);
        return
      }
      const newFileBox = fileBox ? [target, ...fileBox] : [target];
      form.setValuesIn('fileBox', newFileBox);
    }
    form.setValuesIn('code', undefined);
  }, 500)

  const handleAfterPrint = () => {
    Modal.confirm({
      title: '是否清空数据?',
      onOk: () => {
        setPrintList([]);
        setSubmited(false);
        formRef.current?.reset();
      },
    });
  }

  const renderFooter = () => {
    return <div style={{
      position: 'absolute',
      left: 0,
      bottom: 0,
      display: 'flex',
      justifyContent: 'flex-end',
      padding: 16,
      marginTop: 17,
      width: '100%',
      backgroundColor: '#fff',
      zIndex: 100
    }}>
      {
        submited ?
          <ReactToPrint
            ref={(e) => printCmpntRef.current = e}
            onAfterPrint={handleAfterPrint}
            trigger={() => <Button type="primary">打印预览</Button>}
            content={() => printContentRef.current}
          /> :
          <Button type="primary" onClick={submit}>提交</Button>
      }
    </div>;
  };

  return (
    <>
      <BillFormLayout
        anchor
        type="NORMAL"
        pageCode="ArcvFileBox_Cbnt_C"
        events={{}}
        formConfigs={{
          effects: () => {
            onFormMount((form) => {
              formRef.current = form;
            })
            onFieldInit('code', (field: any, form) => {
              field.componentProps.onInput = async (e: any) => {
                const { fileBox } = form.values;
                const code = e.target.value;

                if (!code || fileBox?.some((o: any) => o.code === code)) {
                  const times = setTimeout(() => {
                    clearTimeout(times);
                    form.setValuesIn('code', undefined);
                  }, 500);
                  message.error(`档案盒 ${code} 已在档案盒列表`);
                  return;
                };

                searchFileBox(form, code);
              }
            })
            onFieldInit('fileBox', (field, form) => {
              field.componentProps = {
                ...field.componentProps,
                checkClickFn: () => {
                  if (!form.values?.belongCo) {
                    message.error('请先选择保管公司');
                    return false;
                  }
                  return true;
                }
              }
            })
            onFieldChange('belongCo', (field: any, form) => {
              form.setFieldState('whseCode', st => {
                st.componentProps = _.merge(st.componentProps, {
                  disabled: !field.value,
                  api: {
                    params: {
                      queryKeys: {
                          belongCo: field.value,
                          pageCode: 'ArcvWhse_L'
                      }
                    }
                  }
                })
              })
              form.setFieldState('cbntCode', st => {
                st.componentProps = _.merge(st.componentProps, {
                  disabled: !field.value,
                  api: {
                    params: {
                      queryKeys: {
                        belongCo: field.value
                      }
                    }
                  }
                })
              })
              form.setFieldState('fileBox', (state: any) => {
                state.componentProps = {
                  ...state.componentProps,
                  extraPrams: {
                    coCode: field.value
                  },
                }
              })
              if (!field.modified) return;

              const { code } = form.values;

              !!code && searchFileBox(form, code);
              form.setValuesIn('whseCode', undefined);
              form.setValuesIn('cbntCode', undefined);
              form.setValuesIn('whseCodeName', undefined);
              form.setValuesIn('belongCoName', field.inputValues?.[1]?.name);
            })
            onFieldChange('whseCode', (field: any, form) => {
              form.setFieldState('cbntCode', st => {
                st.componentProps = _.merge(st.componentProps, {
                  disabled: !field.value,
                  api: {
                    params: {
                      queryKeys: {
                        whseCode: field.value
                      }
                    }
                  }
                })
              })
              if (!field.modified) return;
              form.setValuesIn('cbntCode', undefined);
            })
          },
        }}
        filedConfig={{}}
        needFooter={false}
        insertInfoRender={() => {
          return <div style={{ height: 50 }}></div>;
        }}
      />
      {renderFooter()}
      <div style={{ display: 'none' }}>
        <div ref={(el) => (printContentRef.current = el)}>
          <BarPrint list={printList} />
        </div>
      </div>
    </>
  );
};

export default ArchivesCabinet;
